/*
 * License: Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 * Description: pull stream
 * Date: 2020-01-07 10:37:06
 * LastEditTime : 2020-02-12 19:24:48
 */
#ifndef SRC_ENGINE_H
#define SRC_ENGINE_H

#include <atomic>
#include <thread>
#include <queue>
#include "hiaiengine/engine.h"
#include "trans_data.h"
extern "C" {
#include "libavformat/avformat.h"
}
using namespace std;

#define RP_INPUT_SIZE 1
#define RP_OUTPUT_SIZE 1

class MediaInherentAttr {
public:
    int videoFormat;
    int outputFormat;
    int vencFrameRate;
    int vencBitRate;
    int vencCtlType;

    void SetAttr(int videoFormat, int outFormat, int frameRate, int bitRate, int vencCtlType)
    {
        this->videoFormat = videoFormat;
        this->outputFormat = outFormat;
        this->vencFrameRate = frameRate;
        this->vencBitRate = bitRate;
        this->vencCtlType = vencCtlType;
    }
};

struct PacketInfo {
    shared_ptr<uint8_t> buf;
    uint32_t len;
    uint64_t frameNum;
    float fps;
};

class SrcEngine : public hiai::Engine {
public:
    HIAI_StatusT Init(const hiai::AIConfig& config, const vector<hiai::AIModelDescription>& model_desc);
    ~SrcEngine();
    HIAI_DEFINE_PROCESS(RP_INPUT_SIZE, RP_OUTPUT_SIZE)
private:
    int GetStreamInfo(shared_ptr<AVFormatContext>, int&, int&);
    void PullStreamDataLoop();
    uint64_t GetCurentTimeStamp();
    HIAI_StatusT StartStream();
    void TransferData();
    int ReadFrame(shared_ptr<AVFormatContext> pFormatCtx, uint64_t& frameNum, int videoIndex);
    shared_ptr<AVFormatContext> CreateFormatContext(string streamName);
    HIAI_StatusT SendPacketInfo(shared_ptr<TransData> output);

    thread pullStreamThread;
    thread sendDataThread;

    // stream info
    int graphId = -1;
    int deviceId = -1;
    int channelId = -1;
    MediaInherentAttr mediaAttr;
    uint64_t initTimeStamp = 0;
    atomic<int> stop = {0};
    mutex mtx;
    queue<shared_ptr<PacketInfo>> dataQueues;
};

#endif